//
//  HBMyMsgListCtrl.m
//  HuoBao
//
//  Created by chaiyanan on 15/12/7.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "HBMyMsgListCtrl.h"
#import "HBMyMsgListCell.h"
#import "HBMyMsgDetailCtrl.h"

#import "MJRefresh.h"
#import "HBGetUserMsgListParam.h"
#import "HBGetUserMsgListParser.h"
#import "HBGetUserMsgListInfo.h"
#import "HBGetUserMsgListItemInfo.h"

@interface HBMyMsgListCtrl ()
<UITableViewDataSource,
UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) HBGetUserMsgListInfo *msgListInfo;
@property (nonatomic) int pageNum;

@property (nonatomic, strong) UIImageView *emptyIV;

@end

@implementation HBMyMsgListCtrl

#pragma mark - system

- (void)viewDidLoad
{
    [super viewDidLoad];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
}

- (void)buildLayout
{
    [super buildLayout];
    self.title = @"消息";
    self.pageNum = 1;
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    [self.view addSubview:_tableView];
    INIT_TABLE(_tableView);
    
    __weak UITableView *tableView = self.tableView;
    __weak typeof(self) weakSelf = self;
    
    // 下拉刷新
    tableView.mj_header = [HBOrangeHeader headerWithRefreshingBlock:^{
        
        [weakSelf hideEmptyIV];
        weakSelf.pageNum = 1;
        [weakSelf requestToGetBankList];
        
        
        //        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        //        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //            // 结束刷新
        //            [tableView.mj_header endRefreshing];
        //        });
    }];
    
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    tableView.mj_header.automaticallyChangeAlpha = YES;
    
    // 上拉刷新
    tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        //        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        //        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //            // 结束刷新
        //            [tableView.mj_footer endRefreshing];
        //        });
        
        if (weakSelf.msgListInfo.dataAry.count>0)
        {
            weakSelf.pageNum++;
            [weakSelf requestToGetBankList];
        }
        else
        {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                // 结束刷新
                [tableView.mj_footer endRefreshing];
            });
        }
        
    }];
    
//    [self.tableView.mj_header beginRefreshing];
    self.pageNum = 1;
    [self requestToGetBankList];

    
}

#pragma mark - private

- (void)showEmptyIV
{
    self.emptyIV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"My_Msg_Empty"]];
    self.emptyIV.center = self.tableView.center;
    self.emptyIV.center = CGPointMake(self.emptyIV.center.x, self.emptyIV.center.y-32);
    [self.view addSubview:self.emptyIV];
}

- (void)hideEmptyIV
{
    [self.emptyIV removeFromSuperview];
    self.emptyIV = nil;
}

- (void)uploadMyMsgListCell:(HBMyMsgListCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    HBGetUserMsgListItemInfo *itemInfo = self.msgListInfo.dataAry[indexPath.row];
    
    double lastactivityInterval = [itemInfo.msgTime doubleValue]/1000;
    
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy.MM.dd"];
    
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:lastactivityInterval];
    NSString* dateString = [formatter stringFromDate:date];
    
    cell.timeLable.text = dateString;
    [cell setTitle:itemInfo.msgTitle andSubTitle:itemInfo.msgContent];
}

- (CGFloat)getMsgCellHeightWithSubTitle:(NSString *)subTitle
{
    //@"好玩好赚-送体验金官方，赢了随时换钱，刺激火爆-送体验金下载，好赢就是硬道理！送体验金官方，24小时客服兑分服务，网络顶级送体验金平台"
    
    UILabel *subTitleLable = [self createLableWithTextColor:[LCCommon getColor:@"999999"] font:[UIFont systemFontOfSize:13.0f] text:subTitle textAlignment:NSTextAlignmentLeft frame:CGRectMake(900, 36+14, SCREEN_WIDTH-30, 50.0f) superView:self.view numberOfLines:3];
    
    CGRect lableFrame = subTitleLable.frame;
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:subTitle];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    [paragraphStyle setLineSpacing:8];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, subTitle.length)];
    subTitleLable.attributedText = attributedString;
    [subTitleLable sizeToFit];
    
    CGRect lableFrameNew = subTitleLable.frame;
    lableFrameNew.origin = lableFrame.origin;
    subTitleLable.frame = lableFrameNew;
    
    LLog(@"subTitle.frame:%@",NSStringFromCGRect(subTitleLable.frame));
    
    CGFloat height = subTitleLable.y + subTitleLable.height + 20;
    
    [subTitleLable removeFromSuperview];
    
    return height;
    
}

- (UILabel *)createLableWithTextColor:(UIColor *)color font:(UIFont *)font text:(NSString *)text textAlignment:(NSTextAlignment)textAlignment frame:(CGRect)frame superView:(UIView *)superView numberOfLines:(NSInteger)numberOfLines
{
    UILabel *lable = [[UILabel alloc]initWithFrame:frame];
    lable.textColor = color;
    lable.font = font;
    lable.text = text;
    lable.textAlignment = textAlignment;
    lable.numberOfLines = numberOfLines;
    [superView addSubview:lable];
    return lable;
}


#pragma mark - active



#pragma mark - delegate&datasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.msgListInfo.dataAry.count>0&&self.msgListInfo.dataAry) {
        
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.msgListInfo.dataAry.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = NSStringFromClass([HBMyMsgListCell class]);;
    
    HBMyMsgListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (!cell)
    {
        cell = [[HBMyMsgListCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [self uploadMyMsgListCell:(HBMyMsgListCell *)cell atIndexPath:indexPath];
    
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1/[UIScreen mainScreen].scale;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1/[UIScreen mainScreen].scale)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HBGetUserMsgListItemInfo *itemInfo = self.msgListInfo.dataAry[indexPath.row];
    return [self getMsgCellHeightWithSubTitle:itemInfo.msgContent];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    HBGetUserMsgListItemInfo *itemInfo = self.msgListInfo.dataAry[indexPath.row];
    if (itemInfo.msgUrl.length>0)
    {
        HBMyMsgDetailCtrl *detailCtrl = [[HBMyMsgDetailCtrl alloc]init];
        detailCtrl.webUrl = itemInfo.msgUrl;
        [self.navigationController pushViewController:detailCtrl animated:YES];
    }
    
    
}

#pragma mark - net

- (void)requestToGetBankList
{
        [CustomLoadingView showHudToView:self.view];
        HBGetUserMsgListParam *param = [[HBGetUserMsgListParam alloc]init];
        param.uid = [HBLoginManager sharedHBLoginManager].currentUserInfo.uid;
        param.token = [HBLoginManager sharedHBLoginManager].currentUserInfo.token;
        param.pageNum = [NSString stringWithFormat:@"%d",self.pageNum];
        HBGetUserMsgListParser *parser = [[HBGetUserMsgListParser alloc]init];
        [NetCenter getDataFromURL:Method_getUserMsgList params:param parser:parser result:^(ParserResult *myResult) {
            [CustomLoadingView hideHudForView:self.view];
            if (self.pageNum==1)
            {
                [self.tableView.mj_header endRefreshing];
            }
            else
            {
                [self.tableView.mj_footer endRefreshing];
            }

            if (myResult.code==0)
            {
                HBGetUserMsgListInfo *listInfo = (HBGetUserMsgListInfo *)myResult.result;
                if (self.pageNum==1)
                {
                    self.msgListInfo = listInfo;
                    [self.tableView reloadData];
                    if (self.msgListInfo.dataAry.count==0)
                    {
                        [self showEmptyIV];
                    }
                    else
                    {
                        if (self.tableView.mj_footer)
                        {
                            [self.tableView.mj_footer resetNoMoreData];
                        }
                    }
                }
                else
                {
                    if (listInfo.dataAry.count>0)
                    {
                        NSMutableArray *array = [NSMutableArray arrayWithArray:self.msgListInfo.dataAry];
                        [array addObjectsFromArray:listInfo.dataAry];
                        self.msgListInfo.dataAry = array;
                        [self.tableView reloadData];
                    }
                    else
                    {
                        self.pageNum--;
                        [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    }
                }
//                self.msgListInfo = listInfo;
//                [self.tableView reloadData];
            }
            else
            {
                DISSMISS_ERR(myResult.message);
                if (self.pageNum>1)
                {
                    self.pageNum--;
                }
            }
    
        } failure:^(NSError *error) {
            [CustomLoadingView hideHudForView:self.view];
            DISSMISS_ERR([error description]);
            if (self.pageNum==1)
            {
                [self.tableView.mj_header endRefreshing];
            }
            else
            {
                [self.tableView.mj_footer endRefreshing];
                self.pageNum--;
            }

        }];
}


@end
